from selenium import webdriver
import time
from PIL import ImageGrab

class Utility:

    driver = None   # 类级变量，跟随类内存空间而不随实例内存空间

    def __init__(self):
        pass

    # 实例化一个WebDriver，供其他所有测试脚本调用，并确保返回唯一的一个Driver实例（单例模式）
    @classmethod    # 类方法：直接通过类名调用，不需要通过实例来调用的方法，与@staticmethod类似
    def get_webdriver(cls):
        if cls.driver == None:
            cls.driver = webdriver.Firefox()
            cls.driver.implicitly_wait(3)
            cls.driver.maximize_window()
            cls.driver.get('http://localhost:8088/woniusales')
            time.sleep(2)
        # print(id(cls.driver))
        return cls.driver


    @classmethod
    def assert_equal(cls, expect, actual, case):
        if expect == actual:
            cls.write_result(case, '成功')
        else:
            cls.write_result(case, '失败')

    @classmethod
    def assert_true(cls, actual, case):
        if actual == True:
            cls.write_result(case, '成功')
        else:
            cls.write_result(case, '失败')

    @classmethod
    def write_result(cls, case, result):
        if result == '成功':
            filename = '无'
        elif result == '失败':
            filename = cls.capture()
        else:
            raise Exception('你的参数有误，只接收[成功]和[失败]两种结果，而你的结果是：%s' % result)
        test_time = time.strftime("%Y-%m-%d %H:%M:%S")


    @classmethod
    def generate_html(cls):
        table = '''
<html>
<head>
<meta charset="utf-8">
</head>
<style>
    tr {
    }
</style>
<table width=1000 border=1 cellspacing=0 align=center>
    <tr bgcolor=orange>
        <td width=25%>测试时间</td>
        <td width=35%>测试用例</td>
        <td width=15%>测试结果</td>
        <td width=25%>错误截图</td>
    </tr>     
        '''

        with open('../report/result.csv', encoding='utf-8') as file:
            content = file.readlines()

        for line in content:
            table += "<tr>\n"
            table += " <td width=25%%>%s</td>\n" % line.strip().split(',')[0]
            table += " <td width=35%%>%s</td>\n" % line.strip().split(',')[1]

            result = line.strip().split(',')[2]
            if result == '成功':
                table += " <td width=15%% bgcolor=green>%s</td>\n" % result
            else:
                table += " <td width=15%% bgcolor=red>%s</td>\n" % result

            screen = line.strip().split(',')[3]
            if screen == '无':
                table += " <td width=25%%>%s</td>\n" % screen
            else:
                table += " <td width=25%%><a href='../screenshot/%s'>%s</a></td>\n" % (screen, screen)

            table += "</tr>\n"

        table += "</table>"

        with open('../report/report.html', mode='w', encoding='utf-8') as file:\
            file.write(table)

    @classmethod
    def capture(cls):
        filename = time.strftime("%Y%m%d_%H%M%S.png")
        ImageGrab.grab().save("../screenshot/" + filename)
        return filename

if __name__ == '__main__':
    Utility.generate_html()